<?php

header('Access-Control-Allow-Origin:*');

require_once 'WxConfig.php';
require_once 'WxFunction.php';
require_once 'WxApi.php';
require_once 'WxAes.php';
WxAes::$_key = WxConfig::KEY;

if(empty($_GET['url'])) WxFunction::ajaxReturn(NULL, 'Invalid url', 1);

/**
 * 生成随机字符串
 * @param int $length 默认为16位
 * @return string
 */
function createNonceStr($length = 16)
{
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $str = '';
    for ($i = 0; $i < $length; $i++){
        $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
}

$jsapiTicket = WxApi::getJsApiTicket();
$timestamp = time();
$nonceStr = createNonceStr();

// 这里参数的顺序要按照 key 值 ASCII 码升序排序
$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url={$_GET['url']}";

$signature = sha1($string);

WxFunction::ajaxReturn(array(
    "appId"     => WxConfig::APPID,
    "nonceStr"  => $nonceStr,
    "timestamp" => $timestamp,
    "url"       => $_GET['url'],
    "signature" => $signature,
    "rawString" => $string,
));